<template>

  <div style="display: flex;justify-content: space-between">
    <h1><b>订单状态：<span :status="detail?.ostat">{{ STATUS[detail?.ostat] }}</span></b></h1>
  </div>

  <!--订单动态-->
  <div class="block">
    <div style="display: flex;justify-content: space-between">
      <h1><b>订单动态</b></h1>
      <a-button type="link" @click="showTrackModal()">添加跟进</a-button>
    </div>

    <a-table :columns="trackTableColumns" :data-source="trackList" :scroll="{ x: 1200, y: 300 }">
      <template #bodyCell="{ column,record,text }">
        <template v-if="column.dataIndex === 'content'">
          {{ text[0] }}
          <a-button v-if="record?.expressNo" type="link" @click="showExpressTrack(record?.expressNo)">
            {{ record?.expressNo }}
          </a-button>
          {{ text[1] }}
        </template>
      </template>
    </a-table>

  </div>

  <!--订单信息-->
  <div class="block">
    <div style="display: flex;justify-content: space-between">
      <h1><b>订单信息</b></h1>
      <a-button v-if="detail.ostat===10" type="link" @click="cancelOrder()">取消订单</a-button>
    </div>
    <div style="padding-left: 32px;">
      <span style="margin-right: 16px">订单编号：{{ detail?.orderKey }}</span>
      <span :status="detail?.ostat" style="margin-right: 16px">订单状态：{{ STATUS[detail?.ostat] }}</span>
      <span style="margin-right: 16px">下单方式：{{ detail?.orderWay === 1 ? '估价下单' : '批量下单' }}</span>
      <span v-if="detail?.otime" style="margin-right: 16px">下单时间：{{ detail?.otime }}</span>
      <span v-if="detail?.otime11" style="margin-right: 16px">揽件时间：{{ detail?.otime11 }}</span>
      <span v-if="detail?.otime12" style="margin-right: 16px">签收时间：{{ detail?.otime12 }}</span>
      <span v-if="detail?.otime33" style="margin-right: 16px">打款时间：{{ detail?.otime33 }}</span>
    </div>
    <div v-if="detail?.otime88" style="padding-left: 32px;">
      取消时间：{{ detail?.otime88 }}
    </div>
  </div>

  <!--取件信息-->
  <div class="block">
    <div style="display: flex;justify-content: space-between">
      <h1><b>取件信息</b></h1>
    </div>
    <div style="padding-left: 32px;">
      <span style="margin-right: 16px">寄件人姓名：{{ detail?.logistics?.lnker }}</span>
      <span style="margin-right: 16px">联系电话：{{ detail?.logistics?.lnktel }}</span>
      <span>取件时间：{{ detail?.logistics?.apptime }}</span>
    </div>
    <div style="padding-left: 32px;">
      取件地址：{{ detail?.logistics?.exparea.replace(/@/g, ' ') }} {{ detail?.logistics?.expdtl }}
    </div>
    <div style="padding-left: 32px;">
      平台地址：占位
    </div>
  </div>

  <!--收款信息-->
  <div class="block">
    <div style="display: flex;justify-content: space-between">
      <h1><b>收款信息</b></h1>
      <a-button v-if="[10,11,12,13,30,31,32].includes(detail.ostat)" type="link" @click="editPayee()">编辑
      </a-button>
    </div>
    <div style="padding-left: 32px;">
      <span style="margin-right: 16px">账户类型：支付宝</span>
      <span style="margin-right: 16px">收款账户：{{ detail?.payacc || '-' }}</span>
      <span>收款人姓名：{{ detail?.payname || '-' }}</span>
    </div>
    <div v-if="detail.ostat===32">
      <a-button @click="payAgain">申请打款</a-button>
    </div>
  </div>

  <!--下单信息-->
  <div class="block">
    <h1><b>下单信息</b></h1>
    <div v-if="detail.orderWay===1" style="padding-left: 32px;display: flex;margin-top: 8px">
      <img :src="detail.oriModelIcon" style="height: 80px;width: 80px">
      <div>
        <div style="margin-bottom: 4px">{{ detail.oriModelName }}</div>
        <div style="margin-bottom: 4px">预估回收价格：<span style="color: #FA3131">￥{{ detail.mrp }}</span></div>
        <div style="display: flex;align-items: center">
          <a-tooltip :title="detail.evalCopy">
          <span
              style="display: inline-block;max-width: 400px;overflow: hidden;text-overflow: ellipsis;white-space: nowrap">
            {{ detail.evalCopy }}
          </span>
          </a-tooltip>
          <a-button type="link" @click="showEvaluateDetail()">评估详情></a-button>
        </div>
      </div>
    </div>
    <div v-if="detail.orderWay===2" style="padding-left: 32px;display: flex;margin-top: 8px">
      手机 X{{ detail.phoneNum }} 平板 X{{ detail.padNum }}
    </div>
  </div>

  <!--质检信息-->
  <div class="block">
    <div style="display: flex;justify-content: space-between;margin-bottom: 8px">
      <div style="display: flex;align-items: center;flex-direction: row;">
        <span style="font-weight: bold;font-size: 1.17em">质检信息</span>
        <a-button type="link" @click="setPointer">设置打印机</a-button>
      </div>
      <div>
        <!--        <a-button v-if="detail.showPushFlag===1" :disabled="!checkedDevices.length||getPushCheckReportBtn()"-->
        <a-button v-if="detail.showPushFlag===1"
                  style="margin-right: 8px"
                  type="primary"
                  @click="showPushCheckReportDialog()">推送质检报告
        </a-button>
        <a-button :disabled="!([10,11,12,13,20].includes(detail.ostat)&&(!detail.checkId||(userId===detail.checkId)))"
                  type="primary"
                  @click="addDevice()">添加机器
        </a-button>
      </div>
    </div>

    <a-table :columns="checkedDeviceTableColumns" :data-source="checkedDevices" :scroll="{ x: 1500, y: 300 }">
      <template #bodyCell="{record, column,text }">
        <template v-if="column.dataIndex === 'status'">
          {{ CHECKSTATUS[text] }}
          <InfoCircleOutlined v-if="record.status===1" :title="JSON.parse(record.resultBak).join(',')"
                              style="color: red"/>
          <a-button v-if="record.status===1" type="link" @click="showTrackModalByCheck(record.id)">添加</a-button>
        </template>
        <template v-if="column.dataIndex === 'operation'">
          <!--            点打印则打印该机器的标签纸-->
          <a-button type="link" @click="printDeviceInfo(record)">打印</a-button>
          <!--            查看机器：点击则跳到库存管理并按机器编码筛选出该机器-->
          <a-button type="link" @click="toInventory(record)">查看机器</a-button>
          <!--            点质检是进入该机器的质检页面，查看质检信息，并根据订单状态决定是否可编辑(仅质检中可编辑)-->
          <a-button v-if="record.showCheckFlag===1" type="link" @click="toCheckDevice(record)">质检</a-button>
          <a-button type="link" @click="showQualityReportModal(record)">查看质检报告</a-button>
          <a-button v-if="record.showDeleteFlag===1" danger type="link" @click="deleteCheckDevice(record.id)">删除
          </a-button>
        </template>
      </template>
    </a-table>

    <div style="display: flex;justify-content: flex-end">
      <span style="font-weight: bold;font-size: 1.17em;">实际回收价格：<span style="color: #FA3131">￥{{
          detail.brp
        }}</span></span>
    </div>

    <div v-if="detail.ostat===30" style="text-align: right;margin-top: 8px">
      <a-button style="margin-right: 24px" @click="showRejectRecycleModal">拒绝回收</a-button>
      <a-button type="primary" @click="confirmRecycle">确认回收</a-button>
    </div>
  </div>


  <!--退货信息-->
  <div v-if="detail.ostat===21" class="block">
    <div style="display: flex;align-items: center;justify-content: space-between">
      <div>
        <span style="font-weight: bold;font-size: 1.17em">退货信息</span>
        <a-button type="link" @click="showRejectRecycleModal">编辑</a-button>
      </div>
      <a-button type="link" @click="showGenerateDeliveryModal">生成出库单</a-button>
    </div>
    <div style="padding-left: 32px;">
      <span style="margin-right: 16px">寄件人姓名：{{ detail?.backLogistics?.lnker }}</span>
      <span style="margin-right: 16px">联系电话：{{ detail?.backLogistics?.lnktel }}</span>
    </div>
    <div style="padding-left: 32px;">
      取件地址：{{ detail?.backLogistics?.exparea.replace(/@/g, ' ') }} {{ detail?.backLogistics?.expdtl }}
    </div>
  </div>


  <!--  评估详情对话框-->
  <a-modal :footer="null" :visible="evaluateModal.visible" title="评估详情" @cancel="evaluateModal.visible=false">
    <div>
      <span style="width: 100px;display: inline-block;">下单机型：</span>
      <span>{{ evaluateModal.detail.modelName }}</span>
    </div>
    <div>
      <span style="width: 100px;display: inline-block;">预估回收价格：</span>
      <span style="color: #FA3131">￥{{ evaluateModal.detail.mrp }}</span>
    </div>
    <a-divider></a-divider>
    <div style="max-height: 400px;overflow-y: auto">
      <div v-for="question in evaluateModal.detail.evalContent">
        <div>
          <b>{{ question.qName }}</b>
        </div>
        <div v-for="option in question.options" style="padding-left: 32px">{{ option.oName }}</div>
      </div>
    </div>
  </a-modal>


  <!--  收款信息对话框-->
  <a-modal :visible="payeeModal.visible" title="收款信息" width="500px"
           @cancel="payeeModalHide" @ok="payeeModalSave">

    <a-row class="row">
      <a-col :span="6" class="rowLabel">收款账号</a-col>
      <a-col :span="18">
        <a-input v-model:value="payeeModal.payacc" placeholder="请输入支付宝账号"/>
      </a-col>
    </a-row>
    <a-row class="row">
      <a-col :span="6" class="rowLabel">收款人姓名</a-col>
      <a-col :span="18">
        <a-input v-model:value="payeeModal.payname" placeholder="请输入支付宝账号真实姓名"/>
      </a-col>
    </a-row>
    <div style="color:red;">注：如订单处于待打款请和财务事先沟通再做编辑</div>
  </a-modal>


  <!--  跟进对话框-->
  <a-modal :visible="trackModal.visible" title="跟进" width="500px"
           @cancel="hideTrackModal" @ok="trackModalSave">
    <a-row class="row">
      <a-col :span="6" class="rowLabel" style="align-self: flex-start"><span class="req">*</span>跟进信息</a-col>
      <a-col :span="18">
        <a-textarea v-model:value="trackModal.content" :maxlength="200" show-count/>
      </a-col>
    </a-row>
  </a-modal>

  <!--  推送质检报告对话框-->
  <a-modal :visible="pushCheckReportModal.visible" title="推送质检报告" width="500px"
           @cancel="hidePushCheckReportModal" @ok="pushCheckReport">
    <a-row class="row">
      <a-col :span="6" class="rowLabel"><span class="req">*</span>质检结果</a-col>
      <a-col :span="18">
        <a-select v-model:value="pushCheckReportModal.checkResultFlag" allowClear placeholder="选择结果"
                  style="width: 260px">
          <a-select-option :value="11">质检结果与评估一致</a-select-option>
          <a-select-option :value="12">质检结果与评估存在差异</a-select-option>
          <a-select-option :value="13">一单多机</a-select-option>
          <a-select-option :value="14">不支持回收</a-select-option>
        </a-select>
      </a-col>
    </a-row>
    <a-row v-if="pushCheckReportModal.checkResultFlag===14" class="row">
      <a-col :span="6" class="rowLabel"></a-col>
      <a-col :span="18">
        <a-radio-group v-model:value="pushCheckReportModal.requiredBack">
          <a-radio :value="14">需要退货</a-radio>
          <a-radio :value="15">无需退货</a-radio>
        </a-radio-group>
      </a-col>
    </a-row>
    <h3 style="color: #FA3131">实际回收价:￥{{ detail.brp }}</h3>
  </a-modal>

  <!--  物流信息对话框-->
  <a-modal :footer="null" :visible="expressTrackModal.visible" title="物流信息"
           width="500px" @cancel="hideExpressTrackModal">
    <div style="max-height: 600px;overflow-y: scroll;padding: 16px">
      <a-timeline>
        <a-timeline-item v-for="item in expressTrackModal.expressData">
          <div>{{ item.remark }}</div>
          <div style="color: #666666">{{ item.acceptTime }}</div>
        </a-timeline-item>
      </a-timeline>
    </div>
  </a-modal>
  <!--  拒绝回收对话框-->
  <a-modal :visible="rejectRecycleModal.visible" title="拒绝回收" width="700px"
           @cancel="hideRejectRecycleModal" @ok="rejectRecycle">
    <div>选择退货信息</div>
    <div>
      <div>
        <a-radio :checked="rejectRecycleModal.type===0" @click="rejectRecycleModal.type=0">使用用户地址</a-radio>
      </div>

      <a-radio-group v-model:value="rejectRecycleModal.checkedUserAddressId" style="margin-left: 32px">
        <a-radio v-for="o in orderUserAddressList" :value="o.id" style="display: flex">
          {{ o.lnker }} {{ o.lnktel }} {{ o.exparea.split('@').join(' ') }} {{ o.expdtl }}
        </a-radio>
      </a-radio-group>
    </div>

    <div style="margin-top: 24px">
      <a-radio :checked="rejectRecycleModal.type===1" @click="rejectRecycleModal.type=1">使用新地址</a-radio>
    </div>
    <a-row class="row">
      <a-col :span="6" class="rowLabel"><span class="req">*</span>收件人：</a-col>
      <a-col :span="18">
        <a-input v-model:value="rejectRecycleModal.userInfo.name" placeholder="请输入收件人" style="width: 300px"/>
      </a-col>
    </a-row>
    <a-row class="row">
      <a-col :span="6" class="rowLabel"><span class="req">*</span>联系方式：</a-col>
      <a-col :span="18">
        <a-input v-model:value="rejectRecycleModal.userInfo.phone" placeholder="请输入收件人联系方式"
                 style="width: 300px"/>
      </a-col>
    </a-row>
    <a-row class="row">
      <a-col :span="6" class="rowLabel"><span class="req">*</span>收件地区：</a-col>
      <a-col :span="18">
        <a-cascader v-model:value="rejectRecycleModal.userInfo.areaCode" :options="regionData"
                    placeholder="请选择"
                    style="width: 400px"
                    @change="areaChange"/>
      </a-col>
    </a-row>
    <a-row class="row">
      <a-col :span="6" class="rowLabel" style="align-self: flex-start"><span class="req">*</span>详细地址：</a-col>
      <a-col :span="18">
        <a-textarea v-model:value="rejectRecycleModal.userInfo.addressDetail" :maxlength="200"
                    placeholder="请输入详细地址"
                    show-count
                    style="width: 400px"/>
      </a-col>
    </a-row>
  </a-modal>

  <!--  质检报告对话框-->
  <a-modal :footer="null" :visible="qualityReportModal.visible" title="质检报告"
           width="600px" @cancel="hideQualityReportModal">
    <div style="display: flex;">
      <a-image
          :height="100"
          :src="qualityReportModal.detail.modelIcon"
          :width="100"
      />
      <div>
        <div v-if="!qualityReportModal.detail?.noSuchFlag?.modelIdNoneItem" style="margin-top: 12px">
          机型名称：{{ qualityReportModal.detail.modelName }}
        </div>
        <div style="color: #FF9736;margin-top: 24px">
          质检结果：{{ QUALITYSTATUS[qualityReportModal.detail.checkResultFlag] || '未知结果' }}
        </div>
      </div>
    </div>
    <a-row>
      <a-col v-if="!qualityReportModal.detail?.noSuchFlag?.colorNoneItem" :span="12">
        颜色：{{ qualityReportModal.detail.color }}
      </a-col>
      <a-col v-if="!qualityReportModal.detail?.noSuchFlag?.storageNoneItem" :span="12">
        存储容量：{{ qualityReportModal.detail.storage }}
      </a-col>
      <a-col v-if="!qualityReportModal.detail?.noSuchFlag?.phoneTypeNoneItem" :span="12">
        购买渠道：{{ qualityReportModal.detail.phoneType }}
      </a-col>
      <a-col v-if="!qualityReportModal.detail?.noSuchFlag?.networkNoneItem" :span="12">
        网络制式：{{ qualityReportModal.detail.network }}
      </a-col>
      <a-col v-if="!qualityReportModal.detail?.noSuchFlag?.batteryHealthNoneItem" :span="12">
        电池健康：{{ qualityReportModal.detail.batteryHealth }}
      </a-col>
    </a-row>

    <div style="max-height: 400px;overflow-y: auto;margin-top: 24px">
      <div v-if="qualityReportModal.detail?.imgs?.length">
        <div style="font-size: 18px;font-weight: bold;height: 46px;line-height: 46px;border-bottom: 1px solid #eeeeee;">
          质检图片
        </div>
        <a-image-preview-group>
          <a-image v-for="item in qualityReportModal.detail.imgs" :height="100"
                   :src="item.url"
                   :width="100"
                   style="vertical-align: top"
          />
        </a-image-preview-group>
      </div>
      <div
          style="font-size: 18px;font-weight: bold;height: 46px;line-height: 46px;border-bottom: 1px solid #eeeeee;margin-top: 24px">
        质检详情
      </div>
      <a-tabs v-model:activeKey="qualityReportModal.activatedTag">
        <a-tab-pane :key="1" tab="异常项">
          <div v-for="item in qualityReportModal.detail.errorCheckList" style="font-size: 14px;">
            <div style="font-weight: 500;margin-bottom: 8px;margin-top: 24px;padding-left: 16px;">{{ item.title }}</div>
            <div v-for="item in item.children">
              <div v-if="!item.noneItem"
                   style="height: 60px;background: #FFF9F9;display: flex;align-items: center;justify-content: space-between;">
                <div style="display: flex;align-items: center;">
                  <div class="errorDot"></div>
                  <div
                      style="width: 180px;text-align: right;white-space: nowrap;text-overflow: ellipsis;overflow-x: hidden;">
                    {{ item.subject }}：
                  </div>
                  <!-- 单选 -->
                  <div v-if="item.optionType===1">
                    <span v-for="option in item.options"><span v-if="item.radioSelected===option.value"
                                                               style="color:#666666">{{ option.label }}</span></span>
                  </div>
                  <!-- 多选 -->
                  <div v-else style="white-space: nowrap;text-overflow: ellipsis;overflow-x: hidden;width: 250px;">
                    <span v-for="option in item.options"><span v-if="item.checkedSelected.includes(option.value)"
                                                               style="color:#666666;margin-right: 4px">{{
                        option.label
                      }} </span></span>
                  </div>
                </div>
                <div v-if="item.imgLists.length"
                     style="position: relative;margin-right: 8px;display: inline-block;width: 60px;height: 60px;overflow: hidden">
                  <a-image-preview-group>
                        <span v-for="url in item.imgLists">
                          <a-image
                              :height="60"
                              :src="url"
                              :width="60"
                          /></span>
                  </a-image-preview-group>
                </div>
              </div>
            </div>
          </div>
        </a-tab-pane>
        <a-tab-pane :key="2" force-render tab="正常项">
          <div v-for="item in qualityReportModal.detail.rightCheckList" style="font-size: 14px;">
            <div style="font-weight: 500;margin-bottom: 8px;margin-top: 24px;padding-left: 16px;">{{ item.title }}</div>
            <div v-for="item in item.children">
              <div v-if="!item.noneItem"
                   style="height: 60px;background: #F7FFF6;display: flex;align-items: center;justify-content: space-between;">
                <div style="display: flex;align-items: center;">
                  <div class="errorDot" style="color: #97FFA8"></div>
                  <div
                      style="width: 180px;text-align: right;white-space: nowrap;text-overflow: ellipsis;overflow-x: hidden;">
                    {{ item.subject }}：
                  </div>
                  <!-- 单选 -->
                  <div v-if="item.optionType===1">
                    <span v-for="option in item.options"><span v-if="item.radioSelected===option.value"
                                                               style="color:#666666">{{ option.label }}</span></span>
                  </div>
                  <!-- 多选 -->
                  <div v-else style="white-space: nowrap;text-overflow: ellipsis;overflow-x: hidden;width: 250px;">
                    <span v-for="option in item.options">
                      <span v-if="item.checkedSelected.includes(option.value)" style="color:#666666;margin-right: 4px">{{
                          option.label
                        }}</span>
                    </span>
                  </div>
                </div>
                <div v-if="item.imgLists.length"
                     style="position: relative;margin-right: 8px;display: inline-block;width: 60px;height: 60px;overflow: hidden">
                  <a-image-preview-group>
                        <span v-for="url in item.imgLists">
                          <a-image
                              :height="60"
                              :src="url"
                              :width="60"
                          /></span>
                  </a-image-preview-group>
                </div>
              </div>
            </div>
          </div>
        </a-tab-pane>
      </a-tabs>

    </div>
  </a-modal>


  <!--  生成出库单对话框-->
  <a-modal :visible="generateDeliveryModal.visible" title="生成出库单"
           @cancel="hideGenerateDeliveryModal" @ok="submitGenerateDelivery">
    <div>
      <span>邮费承担：</span>
      <span>
    <a-radio-group v-model:value="generateDeliveryModal.freightFlag">
      <a-radio :value="0">我司承担</a-radio>
      <a-radio :value="1">用户承担</a-radio>
    </a-radio-group>
      </span>
    </div>
    <div>确认后将生成回收退货的出库单</div>
  </a-modal>

  <printer ref="printerRef"></printer>

</template>

<script setup>
import {onMounted, reactive, ref, watch} from "vue";
import {useRoute, useRouter} from "vue-router";
import {CHECKSTATUS, orderApi, QUALITYSTATUS, STATUS} from "/@/views/business/order/order";
import {message, Modal} from "ant-design-vue";
import {useUserStore} from "/@/store/modules/system/user";
import {regionData} from "element-china-area-data";
import Printer from "/@/views/business/printer/printer.vue";

const router = useRouter();

const printerRef = ref();
const route = useRoute();
const userId = ref();//当前登录用户id
const previewImgsVisible = ref(false);//当前登录用户id

let orderId = '';//订单id
const detail = reactive({});//订单详情
const trackTableColumns = [
  {
    align: 'center',
    title: '时间',
    dataIndex: 'createTime',
    width: 200,
  },
  {
    align: 'center',
    title: '操作人',
    dataIndex: 'operateUserName',
    width: 120,
  },
  {
    align: 'center',
    title: '操作内容',
    dataIndex: 'content',
    width: 400,
  },
  {
    align: 'center',
    title: '订单状态',
    dataIndex: 'orderOstat',
    width: 180,
  },
  {
    align: 'center',
    title: '跟进信息',
    dataIndex: 'bak',
    ellipsis: true,
  },
]
const trackList = ref([]);//跟进列表
const checkedDevices = ref([]);//已添加质检的机器
const pushReportBtnDisabled = ref(true)
//评估详情对话框
const evaluateModal = reactive({
  visible: false,
  detail: {}
});
// 收款信息对话框
const payeeModal = reactive({
  visible: false,
  payacc: undefined,
  payname: undefined
});
// 跟进对话框
const trackModal = reactive({
  visible: false,
  content: undefined,
  phoneCheckId: undefined,
});
// 推送质检报告对话框
const pushCheckReportModal = reactive({
  visible: false,
  checkResultFlag: undefined,
  requiredBack: 14,
});
// 物流信息对话框
const expressTrackModal = reactive({
  visible: false,
  expressData: []
});
const defaultRejectRecycleModal = {
  visible: false,
  type: 0,
  checkedUserAddressId: undefined,
  userInfo: {
    name: '',
    phone: '',
    areaCode: [],
    areaName: '',
    addressDetail: '',
  }
}
// 拒绝回收对话框
const rejectRecycleModal = reactive({...defaultRejectRecycleModal});
// 推送质检报告对话框
const qualityReportModal = reactive({
  visible: false,
  activatedTag: 1,
  detail: {}
});
// 生产出库单对话框
const generateDeliveryModal = reactive({
  visible: false,
  freightFlag: 0
});

const checkedDeviceTableColumns = ref([
  {
    align: 'center',
    title: '机器编码',
    dataIndex: 'machineCode',
    width: 180,
  },
  {
    align: 'center',
    title: '型号',
    dataIndex: 'modelName',
    width: 180,
  },
  {
    align: 'center',
    title: '质检状态',
    dataIndex: 'status',
    width: 120,
  },
  {
    align: 'center',
    title: '质检价格',
    dataIndex: 'price',
    width: 100,
  },
  {
    align: 'center',
    title: '更新时间',
    dataIndex: 'updateTime',
    width: 120,
  },
  {
    align: 'center',
    title: '操作',
    dataIndex: 'operation',
    width: 300,
  },
])

onMounted(() => {
  orderId = route.query?.id;
  userId.value = useUserStore().employeeId;
  getDetail();
})

function getDetail() {
  orderApi.detail(orderId).then(res => {
    Object.assign(detail, res.data)
  })
  orderApi.getTrackList(orderId).then(res => {
    res.data = res.data.map(item => {
      item.expressNo = item.content.match(/@(.{1,})@/)?.[1];
      item.content = item.content.split(/@.{1,}@/);
      return item;
    })
    trackList.value = res.data;
  })
  orderApi.orderCheckedDevices(orderId).then(res => {
    // checkedDevices.value = res.data;
    checkedDevices.value = res.data;
    pushReportBtnDisabled.value = true;
    res.data.forEach(item => {
      if ([1, 3].includes(item.status)) {
        pushReportBtnDisabled.value = false;
      }
    })
    console.log(res.data)
  })
}

// 显示评估详情
function showEvaluateDetail() {
  orderApi.evaluateDetail(orderId).then(res => {
    evaluateModal.visible = true;
    evaluateModal.detail = res.data;
    console.log(res)
  })
}

// 编辑收款信息
function editPayee() {
  payeeModal.visible = true;
  payeeModal.payacc = detail.payacc;
  payeeModal.payname = detail.payname;
}

function payeeModalHide() {
  payeeModal.visible = false;
  payeeModal.payacc = undefined;
  payeeModal.payname = undefined;
}

function payeeModalSave() {
  if (!payeeModal.payacc || !payeeModal.payacc.trim()) {
    return message.error('请输入支付宝账号');
  }
  if (!payeeModal.payname || !payeeModal.payname.trim()) {
    return message.error('请输入支付宝账号真实姓名');
  }
  orderApi.editPayee(orderId, {
    payacc: payeeModal.payacc,
    payname: payeeModal.payname,
  }).then(() => {
    message.success('操作成功');
    getDetail();
    payeeModalHide();
  })
}

// 取消订单
function cancelOrder() {
  Modal.confirm({
    title: '提示',
    content: '确定要取消该订单吗?',
    okText: '确认',
    okType: 'danger',
    onOk() {
      orderApi.cancelOrder(orderId).then(() => {
        message.success('操作成功');
        getDetail();
      })
    },
    cancelText: '取消',
    onCancel() {
      return Promise.resolve();
    },
  });
}

// 质检中断添加跟进
function showTrackModalByCheck(phoneCheckId) {
  trackModal.visible = true;
  trackModal.phoneCheckId = phoneCheckId;
}

// 显示跟进对话框
function showTrackModal() {
  trackModal.visible = true;
}

// 隐藏跟进对话框
function hideTrackModal() {
  trackModal.visible = false;
  trackModal.content = undefined;
  trackModal.phoneCheckId = undefined;
}

function trackModalSave() {
  if (!trackModal.content || !trackModal.content.trim()) {
    return message.error('请输入跟进信息');
  }
  orderApi.track({
    phoneCheckId: trackModal.phoneCheckId,
    bak: trackModal.content,
    orderId: orderId
  }).then(() => {
    message.success('跟进成功');
    getDetail();
    hideTrackModal();
  })
}

// 添加机器，首次添加需要确认
function addDevice() {
  if (!detail.checkId) {
    Modal.confirm({
      title: '绑定',
      content: '请确认收到机器后再开始新增质检，确定后该订单将绑定在你名下。',
      okText: '确认',
      okType: 'danger',
      onOk() {
        orderApi.bindChecker(orderId).then(() => {
          message.success('绑定成功');
          getDetail();
          router.push({path: '/order/check-device', query: {orderId}});
        })
      },
      cancelText: '取消',
      onCancel() {
        return Promise.resolve();
      },
    });
    return;
  }
  router.push({path: '/order/check-device', query: {orderId}});
}

// 申请再次打款
function payAgain() {
  Modal.confirm({
    title: '提示',
    content: '请确认收款信息已准确无误，申请后订单重新进入待打款状态。',
    okText: '确认',
    okType: 'danger',
    onOk() {
      orderApi.payAgain(orderId).then(() => {
        message.success('操作成功');
        getDetail();
      })
    },
    cancelText: '取消',
    onCancel() {
      return Promise.resolve();
    },
  });
}

function showPushCheckReportDialog() {
  pushCheckReportModal.visible = true;
}

function hidePushCheckReportModal() {
  pushCheckReportModal.visible = false;
  pushCheckReportModal.checkResultFlag = undefined;
  pushCheckReportModal.requiredBack = 14;
}

function pushCheckReport() {
  if (!pushCheckReportModal.checkResultFlag) {
    return message.error('请选择质检结果');
  }
  orderApi.pushCheckReport({
    checkResultFlag: pushCheckReportModal.checkResultFlag === 14 ? pushCheckReportModal.requiredBack : pushCheckReportModal.checkResultFlag,
    orderId
  }).then(() => {
    message.success('推送成功');
    hidePushCheckReportModal();
    getDetail();
  })
}

function getPushCheckReportBtn() {
  let disabled = false;
  checkedDevices.value.forEach(item => {
    if (item.status === 1 || item.status === 3) {
      disabled = true;
    }
  });
  return disabled;
}

function deleteCheckDevice(id) {
  Modal.confirm({
    title: '提示',
    content: '确定要删除吗?',
    okText: '删除',
    okType: 'danger',
    onOk() {
      orderApi.deleteCheckDevice(id).then(() => {
        message.success('删除成功');
        getDetail();
      })
    },
    cancelText: '取消',
    onCancel() {
      return Promise.resolve();
    },
  });
}

// 去质检页面
function toCheckDevice(record) {
  console.log(record);
  router.push({path: '/order/check-device', query: {...record, orderId}});
}

function showExpressTrack(expno) {
  orderApi.getExpressTrack({
    orderId,
    // expno: detail.logistics.expno
    expno
  }).then(res => {
    if(res.data&&res.data.length){
      expressTrackModal.visible = true;
      expressTrackModal.expressData = res.data;
    }else {
      message.error('没有查询到相关物流信息')
    }
    console.log(res)
  })
}

function hideExpressTrackModal() {
  expressTrackModal.visible = false;
  expressTrackModal.expressData = [];
}

const orderUserAddressList = ref([]);

function showRejectRecycleModal() {
  rejectRecycleModal.visible = true;
  orderUserAddressList.value = [];
  orderApi.getOrderUserAddress(orderId).then(res => {
    orderUserAddressList.value = res.data;
    console.log(res)
  })
  // console.log(regionData);
}

function hideRejectRecycleModal() {
  Object.assign(rejectRecycleModal, defaultRejectRecycleModal);
  Object.assign(rejectRecycleModal.userInfo, {
    name: '',
    phone: '',
    areaCode: [],
    areaName: '',
    addressDetail: '',
  });
}

function areaChange(v, selectedOptions) {
  rejectRecycleModal.userInfo.areaName = selectedOptions.map(o => o.label).join('@');
}

function rejectRecycle() {
  if (rejectRecycleModal.type === 0) {
    if (!rejectRecycleModal.checkedUserAddressId) {
      return message.error('请选择退货地址')
    }
    let address = {};
    orderUserAddressList.value.forEach(a => {
      if (a.id === rejectRecycleModal.checkedUserAddressId) {
        address.exparea = a.exparea;
        address.expdtl = a.expdtl
        address.lnker = a.lnker
        address.lnktel = a.lnktel
      }
    })
    orderApi.rejectRecycle(orderId, detail.ostat === 21, {
      exparea: address.exparea,
      expdtl: address.expdtl,
      lnker: address.lnker,
      lnktel: address.lnktel
    }).then(() => {
      message.success('操作成功');
      getDetail();
      hideRejectRecycleModal();
    })
  }
  if (rejectRecycleModal.type === 1) {
    if (!rejectRecycleModal.userInfo.name || !rejectRecycleModal.userInfo.name.trim()) {
      return message.error('请输入收件人姓名')
    }
    if (!/^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/.test(rejectRecycleModal.userInfo.phone)) {
      return message.error('请输入正确的手机号码')
    }
    if (!rejectRecycleModal.userInfo.areaCode.length) {
      return message.error('请选择所在地区')
    }
    if (!rejectRecycleModal.userInfo.addressDetail || !rejectRecycleModal.userInfo.addressDetail.trim()) {
      return message.error('请输入详细地址')
    }
    orderApi.rejectRecycle(orderId, detail.ostat === 21, {
      exparea: rejectRecycleModal.userInfo.areaName,
      expdtl: rejectRecycleModal.userInfo.addressDetail,
      lnker: rejectRecycleModal.userInfo.name,
      lnktel: rejectRecycleModal.userInfo.phone
    }).then(() => {
      message.success('操作成功');
      getDetail();
      hideRejectRecycleModal();
    })
  }
}

function confirmRecycle() {
  Modal.confirm({
    title: '提示',
    content: `确认后用户实际回收价为￥${detail.brp}，是否确认回收?`,
    okText: '回收',
    okType: 'danger',
    onOk() {
      orderApi.confirmRecycle(orderId).then(() => {
        message.success('操作成功');
        getDetail();
      })
    },
    cancelText: '取消',
    onCancel() {
      return Promise.resolve();
    },
  });
}

function showQualityReportModal(data) {
  orderApi.getCheckDeviceDetail(data.id).then(res => {
    res.data.imgs = JSON.parse(res.data.imgs);
    res.data.errorCheckList = [];
    res.data.rightCheckList = [];
    res.data.checkContext = JSON.parse(res.data.checkContext);
    res.data.noSuchFlag = JSON.parse(res.data.noSuchFlag);
    res.data.checkContext.forEach(e => {
      const errorChildren = [];
      const rightChildren = [];
      e.children.forEach(item => {
        if (!item.noneItem && item.optionType === 1) {
          if (item.radioSelected === '0') {
            rightChildren.push(item);
          } else {
            errorChildren.push(item);
          }
        }
        if (!item.noneItem && item.optionType === 2) {
          if (item.checkedSelected?.length && item.checkedSelected[0] === '0') {
            rightChildren.push(item);
          } else {
            errorChildren.push(item);
          }
        }
      });
      // console.log(errorChildren)
      // console.log(rightChildren)
      if (errorChildren.length) {
        res.data.errorCheckList.push({
          ...e,
          children: errorChildren
        })
      }
      if (rightChildren.length) {
        res.data.rightCheckList.push({
          ...e,
          children: rightChildren
        })
      }
    })
    qualityReportModal.detail = res.data;
    qualityReportModal.visible = true;
    console.log(res.data)
  });
}

function hideQualityReportModal() {
  qualityReportModal.visible = false;
  qualityReportModal.activatedTag = 1;
  qualityReportModal.detail = {};
}

function changeTag(index) {
  qualityReportModal.activatedTag = index;
}

function showImgs(data) {
  console.log(data)
}

function setPointer() {
  printerRef.value.showPrinterModal();
}

function printDeviceInfo(data) {
  printerRef.value.printDeviceInfo({
    modelName: data.modelName,
    storage: data.storage,
    serialNumber: data.serialNumber,
    machineCode: data.machineCode
  });
}

function toInventory(record) {
  router.push({path: '/storage/inventory', query: {keyword: record.machineCode}});
}

function showGenerateDeliveryModal() {
  generateDeliveryModal.visible = true;
}

function hideGenerateDeliveryModal() {
  generateDeliveryModal.visible = false;
  generateDeliveryModal.freightFlag = 0;
}

function submitGenerateDelivery() {
  orderApi.generateDeliveryForBack(orderId, generateDeliveryModal.freightFlag).then(() => {
    message.success('操作成功');
    getDetail();
    hideGenerateDeliveryModal();
  })
}

watch(
    () => rejectRecycleModal.type,
    (newValue) => {
      if(newValue===1){
        rejectRecycleModal.checkedUserAddressId = undefined;
      }
    }
);

watch(
    () => rejectRecycleModal.checkedUserAddressId,
    (newValue) => {
      if(newValue!==undefined){
        rejectRecycleModal.type = 0;
      }
    }
);
</script>

<style lang="less" scoped>
.block {
  background-color: white;
  padding: 24px;
  margin-top: 24px;
}


.tag {
  padding: 0 24px;
  box-sizing: border-box;
  white-space: nowrap;
  position: relative;
  height: 40px;
}

.activatedTag {
  display: inline-block;
  font-weight: 500;
  color: #222222;
}

.activatedTag::after {
  content: '';
  width: 80px;
  height: 8px;
  background: #FFEC3D;
  border-radius: 4px;
  position: absolute;
  left: calc(50% - 40px);
  bottom: -4px;
}


.row {
  display: flex;
  flex-direction: row;
  margin-bottom: 8px;
  align-items: center;

  .rowLabel {
    text-align: right;
    padding-right: 8px;

    .req {
      color: red;
    }
  }
}

[status='30'], [status='31'], [status='21'] {
  color: #FF9933;
}

[status='32'] {
  color: red;
}

[status='33'] {
  color: #008000;
}

//.infoIcon {
//  border: 1.4px solid red;
//  width: 18px;
//  height: 18px;
//  border-radius: 10px;
//  display: inline-flex;
//  flex-direction: row;
//  justify-content: center;
//  align-items: center;
//  color: red;
//  font-weight: 600;
//  font-size: 12px;
//  cursor: pointer;
//  position: relative;
//}

.infoIcon:hover:after {
  content: attr(data-title);
  color: rgba(0, 0, 0, .4);
  width: 200px;
  position: absolute;
  top: 18px;
  right: -204px;
  background: white;
  border-radius: 4px;
  border: 1px solid rgba(0, 0, 0, .1);
  opacity: 1;
  z-index: 9999;
  padding: 4px;
}
</style>